<template>
    <el-container class="root">
        <el-header>
            <span>被控设备</span>
            <span class="icon">
                <el-tooltip content="扫描设备" placement="top-start">
                    <el-icon>
                        <Search />
                    </el-icon>
                </el-tooltip>
                <el-tooltip content="添加设备" placement="top-start">
                    <el-icon @click="addDevice">
                        <CirclePlus />
                    </el-icon>
                </el-tooltip>
            </span>
        </el-header>
        <div class="task-card" v-if="tableData && tableData.length">
            <el-scrollbar>
                <div class="content">
                    <div v-for="(element, i) in tableData" :key="i" class="content-list"
                        :class="{ clickCard: currentIndex === i, firstEle: i === 0, lastEle: i === tableData.length - 1 }"
                        @click="sendDeviceName(element, i)">
                        <div class="info">
                            <div class="info-top">
                                <div class="dt">
                                    <div class="label">
                                        <span class="tilEle">
                                            <span class="cus-icon">
                                                <span class="force-svg-16" v-html="deviceIcon"></span>
                                            </span>
                                            <span v-if="!element.isEdit">
                                                {{ `${element.name}` }}
                                            </span>
                                            <el-input v-else v-model="element.name"
                                                @keyup.enter="saveDeviceName(element, i)"
                                                @blur="saveDeviceName(element, i)"></el-input>
                                        </span>
                                        <div class="tool-icon">
                                            <div class="oper">
                                                <el-icon
                                                    :class="{ 'open-status': element.connectState === 'Connected' }"
                                                    @click.stop="openOrClose(element)">
                                                    <SwitchButton />
                                                </el-icon>
                                                <el-popover placement="right" width="auto"
                                                    popper-class="my-information-popover">
                                                    <template #reference>
                                                        <el-icon>
                                                            <Warning />
                                                        </el-icon>
                                                    </template>
                                                    <div class="menu-list">
                                                        <div class="menu-item"
                                                            v-for="(item, index) in element.information" :key="index">
                                                            <div>{{ item.name }}：</div>
                                                            <div class="value" @click="copyContent(item.value)">{{
                                                                item.value }}</div>
                                                        </div>
                                                    </div>
                                                </el-popover>
                                                <el-popover placement="right" width="20px" popper-class="my-popover"
                                                    trigger="click">
                                                    <template #reference>
                                                        <el-icon>
                                                            <MoreFilled />
                                                        </el-icon>
                                                    </template>
                                                    <div class="menu-list">
                                                        <div class="menu-item" @click.stop="modifyName(element)">
                                                            <el-icon>
                                                                <Edit />
                                                            </el-icon>
                                                            <div>重命名设备</div>
                                                        </div>
                                                        <div class="menu-item" @click.stop="deleteDevice(element)">
                                                            <el-icon>
                                                                <Delete />
                                                            </el-icon>
                                                            <div>删除设备</div>
                                                        </div>
                                                    </div>
                                                </el-popover>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="info-bottom">
                                <div v-for="(item, index) in element.information" :key="item.id" class="dt">
                                    <div v-if="index <= 3" class="dl">{{ item.name }}：</div>
                                    <div v-if="index <= 3" class="dr">{{ item.value }}</div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </el-scrollbar>
        </div>
        <div v-else class="null-box">暂无数据</div>
        <el-dialog title="设备添加" v-model="dialogVisible" width="35%" :fullscreen="false">
            <DeviceAdd v-if="dialogVisible" @closeDeviceDialog="closeDeviceDialog"></DeviceAdd>
        </el-dialog>
        <div class="cusDialog">
            <DeviceDetail v-if="deviceDetailDialogVisible" :deviceInformationData="deviceInformationData">
            </DeviceDetail>
        </div>
    </el-container>
</template>
<script setup lang="ts">
import { onMounted, onUpdated, onBeforeUnmount, ref, nextTick, defineEmits, watch } from "vue";
import { ElMessageBox, ElLoading, ElMessage, ElInput } from "element-plus";
import { Search, CirclePlus, SwitchButton, MoreFilled, Delete, Edit, Warning } from '@element-plus/icons-vue';
import DeviceAdd from "./DeviceAdd.vue";
import { sendCommand } from "../../api/manualTest/index";
import { useDeviceViewStore } from "../../store/deviceView";
import type { DeviceInfo } from "../../api/manualTest/index.d";

import deviceIcon from "../../assets/svg/device-icon.svg?raw";

const deviceViewStore = useDeviceViewStore();
const deviceDetailDialogVisible = ref(false);
const dialogVisible = ref(false);
const tableData = ref<DeviceInfo[]>([]);
const clickDeviceName = ref("");
const deviceInformationData = ref("");
const emit = defineEmits(["clearSelfData"]);

onMounted(async () => {
    getDevices();
})

onUpdated(() => {
    removeHoverEnter();
    addHoverEnter();
})

const addHoverEnter = () => {
    const iconInfo = document.querySelectorAll(".el-icon-info");
    if (!iconInfo || !iconInfo.length) return;
    iconInfo.forEach((iconItem: any) => {
        iconItem.addEventListener("mouseenter", handleMouseEnter);
        iconItem.addEventListener("mouseleave", handleMouseLeave);
    });
}

const removeHoverEnter = () => {
    const iconInfo = document.querySelectorAll(".el-icon-info");
    if (!iconInfo || !iconInfo.length) return;
    iconInfo.forEach((iconItem: any) => {
        iconItem.removeEventListener("mouseenter", handleMouseEnter);
        iconItem.removeEventListener("mouseleave", handleMouseLeave);
    });
}

const handleMouseEnter = (e: any) => {
    const cusDialog = document.querySelector(".cusDialog") as HTMLElement;
    if (!cusDialog) return;
    cusDialog.style.display = "block";
    const offsetX = 20; // Adjust as needed
    const offsetY = 20; // Adjust as needed
    cusDialog.style.left = `${e.clientX + offsetX}px`;
    cusDialog.style.top = `${e.clientY + offsetY}px`;
}

const handleMouseLeave = () => {
    const cusDialog = document.querySelector(".cusDialog") as HTMLElement;
    if (!cusDialog) return;
    cusDialog.style.display = "none";
}

const getDevices = async () => {

    const testResult = await sendCommand({}, { commandName: "GetLocalDevices" });
    if (!testResult || !testResult.data) {
        console.error("获取设备失败");
        return;
    }

    const { data }: { data: any[] } = testResult;
    tableData.value = [];
    if (!data || data.length === 0) {
        emit("clearSelfData");
        deviceViewStore.setAllDevices(tableData.value);
        return;
    }
    data.forEach((element: any) => {
        tableData.value.push(element);
    });
    deviceViewStore.setAllDevices(tableData.value);

    nextTick(() => {
        const firstEle = document.querySelector(".firstEle") as HTMLElement;
        firstEle?.click();
    });
}

const deleteDevice = (element: any) => {
    console.log("删除设备元素", element.id);
    ElMessageBox.confirm("确定要删除设备吗", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass"
    }).then(async () => {
        // deviceStore.setDelFlagValue(true);
        await sendCommand({ deviceId: element.id }, { commandName: "RemoveDevice" });
        await getDevices();
        deviceViewStore.removeClickedDevice(element);
        // deviceStore.setDelFlagValue(false);
    }).catch(() => {
        console.log(111);
    });
}

const currentIndex = ref(-1);
const sendDeviceName = (item: any, index: any) => {
    item.deviceIndex = index + 1;
    clickDeviceName.value = `${item.Version}-${item.Name}`;
    deviceViewStore.setCurrentDevice(item);
    deviceViewStore.setClickedDevice(item);
}

watch(
    () => deviceViewStore.currentDevice,
    (val: any) => {
        if (val && val.id) {
            const index = tableData.value.findIndex(item => item.id === val.id);
            if (index !== -1) {
                currentIndex.value = index;
            } else {
                currentIndex.value = -1; // 如果没有找到，重置为-1
            }
        } else {
            currentIndex.value = -1; // 如果没有当前设备，重置为-1
        }
    })

watch(
    () => deviceViewStore.closedDevice,
    async () => {
        await getDevices();
    });

watch(
    () => deviceViewStore.currentDeviceConnStatus,
    () => {
        const findEle = tableData.value.find(x => x.id === deviceViewStore.currentDeviceConnStatus.deviceId);
        if (!findEle) return;
        console.log("状态监控方法执行", deviceViewStore.currentDeviceConnStatus);
        findEle.connectState = deviceViewStore.currentDeviceConnStatus.connectStatus;

    }
)

onBeforeUnmount(() => {
    console.log("组件销毁事件");
})
const addDevice = () => {
    dialogVisible.value = true;
}
const closeDeviceDialog = async () => {
    dialogVisible.value = false;
    await getDevices();
}

const openOrClose = async (element: any) => {
    let methodName = deviceViewStore.openCloseMethodName[0];
    if (element.connectState === "Connected") {
        methodName = deviceViewStore.openCloseMethodName[1];
    }

    console.log("methodName", methodName);

    const deviceId = element.id;

    const loading = ElLoading.service({
        lock: true,
        text: "处理中，请稍后...",
        background: 'rgba(0, 0, 0, 0.7)',
    })

    await sendCommand(
        {
            deviceId
        },
        {
            commandName: methodName
        }).catch((error: any) => {
            console.log("错误", error);
            loading.close();
        })
    loading.close();
    await getDevices();

}

//复制内容
const copyContent = async (content: string) => {
    try {
        await navigator.clipboard.writeText(content);
        ElMessage.success("复制成功！");
    } catch (err) {
        ElMessage.error("复制失败，请检查权限或手动复制");
        console.error('复制失败:', err);
    }
}

const modifyName = (element: DeviceInfo) => {
    element.isEdit = true;
    element.newDeviceName = element.name;

    (document.activeElement as HTMLElement)?.blur();

    nextTick(() => {
        var inputTxt = document.querySelector(".el-input__inner") as HTMLInputElement;
        inputTxt?.focus();
    });

}

const saveDeviceName = async (element: DeviceInfo, index: number) => {
    element.isEdit = false;
    await sendCommand({
        deviceId: element.id,
        newName: element.name
    },
        {
            commandName: "UpdateDeviceName"
        }
    );
    ElMessage.success("设备重命名成功！");
    await getDevices();

    nextTick(() => {
        currentIndex.value = index;
        const clickCardEle = document.querySelector(".clickCard") as HTMLElement;
        clickCardEle?.click();
    });
}

</script>
<style lang="scss">
.el-popover.el-popper {
    min-width: 110px !important;
}

.my-popover {
    .menu-list {
        .menu-item {
            display: flex;
            justify-content: left;
            align-items: center;
            padding: 4px 2px;

            div {
                margin-left: 5px;
            }
        }

        .menu-item:hover {
            cursor: pointer;
            background-color: #dddddd;
        }
    }
}

.my-information-popover {
    width: auto;

    .menu-list {
        .menu-item {
            display: flex;
            justify-content: left;
            align-items: center;
            flex-wrap: nowrap;
            padding: 4px 2px;

            div {
                margin-left: 5px;
            }
        }

        .value:hover {
            cursor: pointer;
            background-color: #dddddd;
        }
    }
}
</style>

<style lang="scss" scoped>
.root {
    display: flex;
    height: 100vh;

    .open-status {
        color: white;
        background-color: green;
        border-radius: 50%;
    }

    .null-box {
        width: 100%;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        color: #909399;
        font-size: 12px;
    }

    .el-header {
        height: 30px !important;
        line-height: 30px;
        background-color: #dddddd;
        font-size: 12px;
        color: #666666;
        font-weight: 500;
        padding-left: 12px;
        display: flex;
        justify-content: space-between;

        .icon {
            i:nth-child(2) {
                margin-left: 10px;
            }

            i {
                cursor: pointer;
                font-size: 14px;
            }
        }
    }

    .task-card {
        flex: 1;
        margin: 25px 20px 20px 25px;
        overflow: auto;

        .content {
            display: flex;
            flex-flow: row wrap;
            align-content: flex-start;
            height: 100%;
            justify-content: space-between;

            .clickCard {
                border: 2px solid #208490 !important;
            }

            .oper {
                width: 30px;
                margin-right: 10px;
                display: flex;
                justify-content: center;
                align-items: center;

            }

            .content-list {
                display: flex;
                border-radius: 4px;
                background-color: #f3f3f3;
                border: 1px solid #d7d7d7;
                width: 96%;
                height: 120px;
                margin-bottom: 18px;
                cursor: pointer;

                &:hover {
                    box-shadow: 0 0 40px rgba(121, 158, 250, 0.11);
                }

                @media (min-width: 760px) and (max-width: 1010px) {
                    width: 49%;
                }

                @media (min-width: 460px) and (max-width: 759px) {
                    width: 95%;
                }

                @media (min-width: 342px) and (max-width: 459px) {
                    width: 95%;
                    height: 210px;
                }

                @media (min-width: 200px) and (max-width: 341px) {
                    width: 95%;
                    height: 350px;
                }

                .info {
                    width: 100%;

                    .info-top {
                        border-bottom: 1px solid #d7d7d7;
                        padding: 18px 14px 0 14px;

                        .cus-icon {
                            display: flex;
                            justify-content: center;

                            // span {
                            //     display: inline-block;
                            //     height: 16px;
                            //     width: 16px;
                            // }

                            .force-svg-16 :deep(svg) {
                                width: 16px !important;
                                height: 16px !important;
                            }

                            .force-svg-16 :deep(svg *),
                            .force-svg-16 :deep(svg) {
                                width: 16px !important;
                                height: 16px !important;
                            }

                        }

                        .dt {
                            align-items: center;
                            margin-bottom: 12px;

                            .label {
                                display: flex;
                                justify-content: space-between;
                                align-items: center;
                                font-size: 12px !important;
                                color: #666666;

                                .tilEle {
                                    display: flex;
                                    justify-content: center;

                                    .cus-icon {
                                        margin-right: 5px;
                                    }
                                }
                            }

                            &:last-of-type {
                                margin-bottom: 6px;
                            }

                            &:first-of-type {
                                margin-bottom: 8px;

                                .label {
                                    line-height: 16px;
                                    // color: #396ff6;
                                    font-size: 12px;
                                    font-weight: 600;

                                    i {
                                        margin-left: 6px;
                                        font-size: 14px;
                                        cursor: pointer;
                                    }

                                    .el-icon-success {
                                        color: lightgreen;
                                    }

                                    .el-icon-info {
                                        color: lightblue;
                                    }

                                    .el-icon-error {
                                        color: rgba(196, 75, 48, 0.737);
                                        // color:red;
                                    }

                                }

                                div {
                                    height: 24px;
                                }
                            }
                        }
                    }

                    .info-bottom {
                        padding: 0px 14px 14px 14px;
                        display: flex;
                        justify-content: flex-start;
                        flex-wrap: wrap;
                        height: 60px;
                        overflow: hidden;

                        .dt {
                            display: flex;
                            justify-content: flex-start;
                            margin-top: 6px;
                            min-width: 50%;
                            box-sizing: border-box;

                            .dl {
                                white-space: nowrap;
                                color: #3c485a;
                                font-size: 12px !important;
                            }

                            .dr {
                                white-space: nowrap;
                                overflow: hidden;
                                text-overflow: ellipsis;
                            }

                            .frequency {
                                margin: 0 8px;
                                color: #616575;
                                font-size: 14px;
                                box-sizing: border-box;
                                border-radius: 2px;
                                background: rgba(57, 111, 246, 0.11);
                            }
                        }
                    }
                }
            }

            .empty {
                content: " ";
                display: flex;
                border-radius: 4px;
                width: calc(29.05% + 2px);
                padding: 14px;
                margin-right: 1%;
                margin-bottom: 18px;
            }
        }
    }

    .cusDialog {
        position: absolute;
        display: none;
        background-color: #f3f3f3;
        border: 1px solid #d7d7d7;
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        border-radius: 5px;
        z-index: 10;
        max-width: 300px;
        overflow-x: auto;
        white-space: nowrap;
    }
}
</style>